import { NextResponse } from 'next/server';
import pool from '@/lib/db';

export async function GET(request, { params }) {
  try {
    const { id } = await params;
    
    // First, get the requested prompt
    const promptResult = await pool.query(
      'SELECT * FROM prompts WHERE id = $1 AND is_public = true',
      [id]
    );

    if (promptResult.rows.length === 0) {
      return NextResponse.json({ error: 'Prompt not found or not public' }, { status: 404 });
    }

    const prompt = promptResult.rows[0];

    // Then, get all versions of this prompt
    const versionsResult = await pool.query(
      'SELECT id, version, created_at FROM prompts WHERE title = $1 AND is_public = true ORDER BY created_at DESC',
      [prompt.title]
    );

    // Attach versions to the prompt object
    prompt.versions = versionsResult.rows || [];

    return NextResponse.json(prompt);
  } catch (error) {
    console.error('Database error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
} 